# Create your views here.
# Create your views here.

from django.contrib.auth import authenticate, login
from django.shortcuts import render_to_response
from museumweb.mainpage.models import Code, LoginForm, RegisterForm, Profile, PaintingForm
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User, Permission

def loginpage(request):
    def errorHandle(error):
            form = LoginForm()
            return render_to_response('mainpage/login.html', {
                                'error': error,
                                'form':form,
                                },context_instance=RequestContext(request))
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid(): 
                username = request.POST['username']
                password = request.POST['password']
                user = authenticate(username=username, password=password)
                if user is not None:
                    if user.is_active:
                        login(request,user)
                        request.session['user']=username
                        return HttpResponseRedirect(reverse("museumweb.mainpage.views.upload"))
                    else:
                        error = u'account disabled'
                        return errorHandle(error)
                else:
                    error = u'invalid login'
                    return errorHandle(error)
        else:
            error = u'form is invalid'
            return errorHandle(error)
    else:
        form = LoginForm()
        return render_to_response('mainpage/login.html',{'form':form},context_instance=RequestContext(request))

def upload(request):
    username = request.session.get('user')
    form = PaintingForm()
    if request.method == 'POST':
        form = PaintingForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            #p = Painting.objects.get(name=request.POST['name'])
            return HttpResponseRedirect(reverse("museumweb.mainpage.views.upload"))
        else:
            data, errors ={}, {}
            
        return render_to_response("mainpage/upload.html",{
                                    'form': form,'error':errors},context_instance=RequestContext(request))
    else:
        return render_to_response("mainpage/upload.html",{
                                    'form': form,'username':username},context_instance=RequestContext(request))
    
#just in case if necessary, form.save() uploads
def handle_uploaded_file(f):
    destination = open(f.name,'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()

def register(request):
    def errorHandle(error):
            form = RegisterForm()
            return render_to_response('mainpage/registration.html', {
                                'error': error,
                                'form':form,
                                },context_instance=RequestContext(request))
    form = RegisterForm()
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            #check code
            code = request.POST['code']
            try:
                museum_obj = Code.objects.get(code=code)
            except Code.DoesNotExist:
                museum_obj = None
                
            if museum_obj:
                museum = museum_obj.museum
            else:
                error = "Not a Valid Code"
                return errorHandle(error)
            #create new user and assign permissions
            newuser = User.objects.create_user(form.cleaned_data['username'],form.cleaned_data['email'],form.cleaned_data['password'])
            perm_painting_add = Permission.objects.get(codename="add_painting")
            perm_painting_change = Permission.objects.get(codename="change_painting")
            perm_painting_delete = Permission.objects.get(codename="delete_painting")
            perm_profile_change = Permission.objects.get(codename="change_profile")
            newuser.user_permissions.add(perm_painting_add,perm_painting_change,perm_painting_delete,perm_profile_change)
            newuser.is_staff=True
            newuser.save()
            
            #create empty profile for new user and save to database
            newprof = Profile(user=newuser)
            newprof.museum = museum
            newprof.save()
            
            #Pull data from form and save to profile in database
            form =  RegisterForm(request.POST, instance=newprof)
            userform = form.save()
            
            #Get username and password
            username=userform.username
            password = userform.password
            
            #Authenticate user and login
            user = authenticate(username=username, password=password)
            login(request,user)
            request.session['user']=username
            
            return HttpResponseRedirect(reverse("museumweb.mainpage.views.upload"))
        else:
            error = "form not valid"
            
        return render_to_response("mainpage/registration.html",{
                                    'form': form,'error':error},context_instance=RequestContext(request))
    else:
        return render_to_response("mainpage/registration.html",{
                                    'form': form,},context_instance=RequestContext(request))
        